﻿using Avalon.Core.Data;
using Avalon.Core.Data.Templates;
using Avalon.Core.MVC.Attributes;
using Avalon.Core.MVC.Helpers;
using Avalon.Core.Providers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace Avalon.Core.MVC.Controllers {
    public class AvalonEntityController : Controller {

        [Renderer(typeof(TableHelper))]
        public ActionResult Index() {
            List<AvalonEntity> entities = 
                RepositoryConfig.Initialize<AvalonEntity>().Get()
                .OrderBy(e => e.Title).ThenBy(e => e.Information).ToList();
            return View(entities);
        }

        [Renderer(typeof(CreateFormHelper))]
        public ActionResult Create() {
            AvalonEntity entity = new AvalonEntity();
            return View(entity);
        }

        [HttpPost]
        public ActionResult Create(AvalonEntity entity) {
            if (ModelState.IsValid) {
                var repository = RepositoryConfig.Initialize<AvalonEntity>();
                repository.Add(entity);
                repository.SaveChanges();

                ProviderContainer.Current.EntityProvider.Reload();

                return RedirectToAction("Index");
            }
            return View(entity);
        }

        [Renderer(typeof(DetailFormHelper))]
        public ActionResult Detail(Guid id) {
            var repository = RepositoryConfig.Initialize<AvalonEntity>();
            var entity = repository.Get(id);
            return View(entity);
        }

        [HttpGet]
        [Renderer(typeof(EditFormHelper))]
        public ActionResult Edit(Guid id) {
            var repository = RepositoryConfig.Initialize<AvalonEntity>();
            return View(repository.Get(id));
        }

        [HttpPost]
        public ActionResult Edit(AvalonEntity entity) {
            if (ModelState.IsValid) {
                var repository = RepositoryConfig.Initialize<AvalonEntity>();
                repository.Update(entity);
                repository.SaveChanges();

                ProviderContainer.Current.EntityProvider.Reload();

                return RedirectToAction("Index");
            }
            return View(entity);
        }

        [HttpGet]
        public ActionResult Initialize() {
            var repository = RepositoryConfig.Initialize<AvalonEntity>();
            IEntityProvider provider = ProviderContainer.Current.EntityProvider;
            foreach (IEntityDescriptor descriptor in provider.GetEntityDescriptors()) {
                AvalonEntity entity = new AvalonEntity() {
                    
                };
            }

            return RedirectToAction("Index");
        }
    }
}
